/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package it.unibo.as.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import java.util.Map;
import javax.servlet.http.HttpSession;
import net.zschech.gwt.comet.server.CometSession;

import it.unibo.as.client.GWTChatService;
import it.unibo.as.client.Message;

/**
 *
 * @author Johnny
 */



public class GWTChatServiceImpl extends RemoteServiceServlet implements GWTChatService {

    //private ConcurrentMap<String, CometSession> users = GWTAccountServiceImpl.users;

    @Override
    public Boolean sendMessage(String m) {
        // check if there is a HTTP session setup.
	HttpSession httpSession = getThreadLocalRequest().getSession(false);
	if (httpSession == null) {
            return Boolean.FALSE;
		//TODO throw new ChatException("not logged in: no http session");
	}

	// get the user name for the HTTP session.
	String username = (String) httpSession.getAttribute("user");
	if (username == null) {
            return Boolean.FALSE;
		//TODO throw new ChatException("not logged in: no http session username");
	}

	// create the chat message
	Message message = new Message();
	message.setUsername(username);
	message.setMessage(m);

	for (Map.Entry<String, CometSession> entry : GWTAccountServiceImpl.users.entrySet()) {
		entry.getValue().enqueue(message);
	}
        return Boolean.TRUE;
    }

}
